<template>
	<view class="container">
		<uv-toast ref="toast"></uv-toast>

		<!-- 商家信息卡片 -->
		<view class="merchant-card" v-if="merchantInfo">
			<view class="merchant-info">
				<image class="merchant-logo" :src="merchantInfo.image || '/static/lyf.jpg'" mode="aspectFill" />
				<view class="merchant-detail">
					<text class="merchant-name">{{ merchantInfo.name }}</text>
					<text class="merchant-address">{{ merchantInfo.street }}</text>
				</view>
			</view>
			<view class="merchant-stats">
				<view class="stat-item">
					<text class="stat-value">{{ statsData.totalIssueCount || 0 }}</text>
					<text class="stat-label">总发放量</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ statsData.totalUseCount || 0 }}</text>
					<text class="stat-label">总使用量</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ statsData.totalUserCount || 0 }}</text>
					<text class="stat-label">用户数量</text>
				</view>
				<view class="stat-item">
					<text class="stat-value">{{ formatPercent(statsData.useRate) }}</text>
					<text class="stat-label">使用率</text>
				</view>
			</view>
		</view>

		<!-- 商家维度统计 -->
		<view class="chart-card">
			<view class="chart-title">商家数据概览</view>
			<canvas canvas-id="merchantChart" id="merchantChart" class="charts" @touchend="tap" />
		</view>

		<!-- 早餐券月度趋势 -->
		<view class="chart-card">
			<view class="chart-title">早餐券月度趋势</view>
			<canvas canvas-id="monthlyChart" id="monthlyChart" class="charts" @touchend="tap" />
		</view>
	</view>
</template>

<script>
	import uCharts from '@/uchart/u-charts-v2.5.0-20230101.js';
	var uChartsInstance = {};

	export default {
		data() {
			return {
				cWidth: 0,
				cHeight: 0,
				merchantId: 0,
				merchantInfo: null,
				statsData: {
					totalIssueCount: 0,
					totalUseCount: 0,
					totalUserCount: 0,
					useRate: 0
				}
			};
		},

		methods: {
			showToast(msg, type = 'default', duration = 1000) {
				this.$refs.toast.show({
					message: msg,
					type: type,
					duration: duration,
				})
			},
			// 格式化百分比
			formatPercent(value) {
				return value ? `${(value * 100).toFixed(1)}%` : '0%';
			},
			// 绘制图表通用方法
			drawCharts(id, data, chartType, opts = {}) {
				const ctx = uni.createCanvasContext(id, this);
				uChartsInstance[id] = new uCharts({
					type: chartType,
					context: ctx,
					width: this.cWidth,
					height: this.cHeight,
					categories: data.categories,
					series: data.series,
					animation: true,
					background: "#FFFFFF",
					color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE"],
					padding: [15, 15, 15, 15], // 修改padding，确保四周留有足够空间
					enableScroll: false,
					legend: {
						show: true,
						padding: 5,
						lineHeight: 11,
						margin: 0,
					},
					xAxis: {
						disableGrid: true,
						fontColor: "#666666",
						fontSize: 12,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2,
						data: [{
							min: 0
						}],
						fontColor: "#666666",
						fontSize: 12,
					},
					...opts
				});
			},
			// 获取商家信息
			async fetchMerchant() {
				try {
					const data = await this.$http.post(`/auth/merchant/info`);
					this.merchantInfo = data;
				} catch (e) {
					this.showToast('商家信息加载失败');
				}
			},
			// 早餐券月度分析
			async fetchMonthlyCouponStatistics() {
				try {
					const data = await this.$http.get(`/analytics/coupon/monthly?merchantId=${this.merchantId}`);
					if (data && data.length) {
						const chartData = {
							series: [{
								data: [{
										name: "发放量",
										value: data[0].couponCount || 0
									},
									{
										name: "使用量",
										value: data[0].usedCount || 0
									},
									{
										name: "用户数",
										value: data[0].uniqueUsers || 0
									}
								]
							}]
						};

						// 使用环形图展示
						this.drawCharts('monthlyChart', chartData, 'ring', {
							title: {
								name: data[0].month,
								fontSize: 15,
								color: '#666666'
							},
							subtitle: {
								name: '当月数据',
								fontSize: 12,
								color: '#999999'
							},
							extra: {
								ring: {
									ringWidth: 30,
									activeOpacity: 0.5,
									activeRadius: 10,
									offsetAngle: 0,
									labelWidth: 15,
									border: true,
									borderWidth: 3,
									borderColor: "#FFFFFF"
								}
							}
						});
					}
				} catch (e) {
					this.showToast('获取月度数据失败', 'error');
				}
			},
			// 获取商家维度统计数据
			async fetchMerchantCouponStatistics() {
				try {
					const data = await this.$http.get(
						`/analytics/coupon/merchant/stats?merchantIds=${this.merchantId}`
					);
					if (data && data.length) {
						// 更新统计数据
						const totalCouponCount = parseInt(data[0].totalCouponCount) || 0;
						const totalUsedCount = parseInt(data[0].totalUsedCount) || 0;

						// 更新统计数据
						this.statsData = {
							totalIssueCount: totalCouponCount,
							totalUseCount: totalUsedCount,
							totalUserCount: parseInt(data[0].totalUserCount) || 0,
							useRate: totalCouponCount > 0 ? Number((totalUsedCount / totalCouponCount).toFixed(
								4)) : 0
						};

						// 使用柱状图展示数据
						const chartData = {
							categories: ['发放总量', '使用总量'], // 修改为两个分类
							series: [{
								name: '数量',
								data: [totalCouponCount, totalUsedCount] // 一个系列包含两个数据点
							}]
						};

						this.drawCharts('merchantChart', chartData, 'column', {
							extra: {
								column: {
									type: "group",
									width: 30,
									activeBgColor: "#000000",
									activeBgOpacity: 0.08
								}
							},
							yAxis: {
								data: [{
									min: 0,
									formatter: (val) => {
										val = parseInt(val);
										if (val >= 10000) {
											return (val / 10000).toFixed(1) + 'w';
										}
										return val;
									}
								}]
							}
						});
					}
				} catch (e) {
					console.error(e);
					this.showToast('获取商家统计数据失败', 'error');
				}
			},
			// 图表交互处理
			tap(e) {
				uChartsInstance[e.target.id].touchLegend(e);
				uChartsInstance[e.target.id].showToolTip(e);
			}
		},

		onReady() {
			const sys = uni.getSystemInfoSync();
			// 考虑容器的padding，所以宽度要减去padding值
			this.cWidth = sys.windowWidth - 60; // 减去左右各30rpx的padding
			this.cHeight = 200; // 设置固定高度
		},

		async onLoad(options) {
			this.merchantId = options.merchantId;
			if (!this.merchantId) {
				this.showToast('商户ID不能为空', 'error');
				return;
			}

			// 等待页面就绪后加载数据
			await this.$nextTick();
			await this.fetchMerchant()
			await Promise.all([
				this.fetchMerchantCouponStatistics(),
				this.fetchMonthlyCouponStatistics(),
			]);
		}
	}
</script>
<style lang="scss" scoped>
	@import 'coupon_stats.scss';
</style>